function post_comment(btn) {
    var form_comment = btn.parent();
    btn.next().show();
    $.ajax({
        url: form_comment.attr('action'),
        type: 'POST',
        data: form_comment.serialize(),
        success: function(msg){
            btn.next().hide();
            msg = eval(msg);
            if (msg.error)
                alert(msg.error);
            else {
                var comment = '<li><a class="avatar" href="/u/' + msg.comment.user.id + '/"><img width="36" height="36" src="' + msg.comment.user.avatar_m + '" alt="" /></a><div class="content"><div class="name_time"><a href="/u/' + msg.comment.user.id + '/">' + msg.comment.user.name + '</a><span>' + msg.comment.date_added + '</span></div><p>' + msg.comment.comment + '</p></div></li>';
                if (form_comment.prev().hasClass('comments'))
                    form_comment.prev().append(comment);
                else
                    form_comment.before('<ul class="comments">' + comment + '</ul>');
                btn.prev().val('');

                var comment_link = form_comment.parent().parent().find('a.comment');
                var comment_text = comment_link.text();
                var comment_count = parseInt(comment_text.substr(3, comment_text.length - 4)) + 1;
                comment_link.text('评论(' + comment_count + ')');
            }
        }
    });
}

$(document).ready(function(){
    var popup = false;
    var popup_marker;
    var options = {
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map_popup = new google.maps.Map(document.getElementById("map_popup"), options);

    $("div.item_stats a.position").live('click', function() {
        if (popup == false) {
            $("#overlayEffect").fadeIn("slow");
            $("#popupContainer").fadeIn("slow");
            $("#close").fadeIn("slow");
            center();
            popup = true;
            var p = $(this).parents('div.trip_item');
            var latlng = new google.maps.LatLng(parseFloat(p.attr('lat')), parseFloat(p.attr('lng')));
            google.maps.event.trigger(map_popup, 'resize');
            if (popup_marker)
                popup_marker.setMap(null);
            popup_marker = new google.maps.Marker({
                position: latlng,
                map: map_popup
            });
            map_popup.setCenter(latlng);
        }
        return false;
    });

    $("div.item_stats a.comment, div.item_stats a.like").live('click', function() {
        if ($(this).attr('href') != '#')
            return;

        var trip_item = $(this).parents('div.trip_item');
        var replies = trip_item.children('div.reply_wrapper');
        if (replies.length > 0)
            replies.remove();
        else {
            var wp_id = trip_item.attr('id');
            var trip_id;
            if ($('#trip_id').length > 0)
                trip_id = $('#trip_id').attr('value');
            else
                trip_id = trip_item.attr('trip_id');
            $.ajax({
                url: '/trips/' + trip_id + '/waypoints/' + wp_id.substr(2, wp_id.length - 2) + '/replies/',
                success: function(html){
                    trip_item.append(html);
                }
            });
        }
        return false;
    });

    $("#close").click(function() {
        hidePopup();
    });

    $("#overlayEffect").click(function() {
        hidePopup();
    });

    function center(){
        var windowWidth = document.documentElement.clientWidth;
        var windowHeight = document.documentElement.clientHeight;
        var popupHeight = $("#popupContainer").height();
        var popupWidth = $("#popupContainer").width();
        $("#popupContainer").css({
            "position": "fixed",
            "top": windowHeight / 2 - popupHeight / 2,
            "left": windowWidth / 2 - popupWidth / 2
        });
    }

    function hidePopup(){
        if (popup == true) {
            $("#overlayEffect").fadeOut("slow");
            $("#popupContainer").fadeOut("slow");
            $("#close").fadeOut("slow");
            popup = false;
        }
    }

    $('a.btn_like').live('click', function() {
        var btn = $(this);
        var form_like = $(this).parent();
        var div_like = form_like.parent();
        form_like.next().show();
        $.ajax({
            url: form_like.attr('action'),
            type: 'POST',
            data: form_like.serialize(),
            success: function(msg){
                form_like.next().hide();
                msg = eval(msg);
                if (msg.error)
                    alert(msg.error);
                else {
                    var count = div_like.find('ul.like_avatars li').length;
                    if (count > 0) {
                        if (msg.id) {
                            if (count == 1) {
                                div_like.children('ul.like_avatars').remove();
                                div_like.children('p.like_title').text('还没有人赞过');
                            } else {
                                div_like.children('ul.like_avatars').find('a[href="/u/' + msg.id + '/"]').parent().remove();
                                var n = parseInt(div_like.children('p.like_title').text()) - 1;
                                div_like.children('p.like_title').text(n + '人觉得很赞');
                            }
                        } else {
                            div_like.children('ul.like_avatars').prepend(msg.html);
                            var n = parseInt(div_like.children('p.like_title').text()) + 1;
                            div_like.children('p.like_title').text(n + '人觉得很赞');
                        }
                    } else {
                        form_like.before('<ul class="like_avatars">' + msg.html + '</ul>');
                        div_like.children('p.like_title').text('1人觉得很赞');
                    }

                    var like_link = form_like.parent().parent().parent().find('a.like');
                    var like_text = like_link.text();
                    var like_count;
                    if (btn.text() == '赞') {
                        btn.text('取消赞');
                        form_like.attr('action', form_like.attr('action').replace('recommend', 'delete_recommend'));
                        like_count = parseInt(like_text.substr(2, like_text.length - 3)) + 1;
                    } else {
                        btn.text('赞');
                        form_like.attr('action', form_like.attr('action').replace('delete_recommend', 'recommend'));
                        like_count = parseInt(like_text.substr(2, like_text.length - 3)) - 1;
                    }
                    like_link.text('赞(' + like_count + ')');
                }
            }
        });
        return false;
    });

    $('a.btn_comment').live('click', function() {
        var btn = $(this);
        post_comment(btn);
        return false;
    });

    $('form.comment').live('submit', function() {
        var btn = $(this).children('a.btn_comment');
        post_comment(btn);
        return false;
    });

    $('ul.comments a.reply').live('click', function() {
        var user_link = $(this).parent().prev().children('a');
        var parts = user_link.attr('href').split('/');
        var user_id = parts[parts.length - 2];
        var form_reply = $(this).parent().parent().parent().parent().next();
        if (form_reply.children('input[name="to"]').length > 0)
            form_reply.children('input[name="to"]').val(user_id);
        else
            form_reply.append('<input type="hidden" name="to" value="' + user_id + '" />');

        var comment_input = form_reply.children('input[name="comment"]');
        var prefix = '回复' + user_link.text() + ': ';
        comment_input.val(prefix);
        comment_input.focus();
        ctrl = comment_input[0];
        pos = prefix.length;
        if(ctrl.setSelectionRange) {
            ctrl.focus();
            ctrl.setSelectionRange(pos, pos);
        } else if (ctrl.createTextRange) {
            var range = ctrl.createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }

        return false;
    });

});
